import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import authService from "../services/auth";
import { Permission, Role, RouteConfig } from "../router/types";

export function usePermission() {
  const navigate = useNavigate();

  return useMemo(
    () => ({
      // 判断用户是否已认证
      isAuthenticated: (): boolean => {
        return authService.getIsAuthenticated();
      },

      // 判断用户是否有角色
      hasRole: (role: Role | Role[]): boolean => {
        return authService.hasRole(role);
      },

      // 判断用户是否有权限
      hasPermission: (permission: Permission): boolean => {
        return authService.hasPermission(permission);
      },

      // 判断用户是否可以访问路由
      canAccess: (route: RouteConfig): boolean => {
        if (!route.meta) return true;

        // 检查是否需要认证
        if (route.meta.requiresAuth && !authService.getIsAuthenticated()) {
          return false;
        }

        // 检查角色
        if (route.meta.roles && route.meta.roles.length > 0) {
          if (!authService.hasRole(route.meta.roles)) {
            return false;
          }
        }

        // 检查权限
        if (route.meta.permissions && route.meta.permissions.length > 0) {
          if (!authService.hasPermission(route.meta.permissions)) {
            return false;
          }
        }

        return true;
      },

      // 重定向到登录页
      redirectToLogin: (): void => {
        navigate("/login", { replace: true });
      },

      // 重定向到未授权页面
      redirectToUnauthorized: (): void => {
        navigate("/unauthorized", { replace: true });
      },
    }),
    [navigate]
  );
}

export default usePermission;
